package day12.util.session;

import day12.attributes.Attributes;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenshijie
 * @date 2023/12/27 14:19
 */

public class SessionUtil {
    // userId -> channel的映射
    private static final Map<Integer, Channel> userIdChannelMap = new ConcurrentHashMap<>();
    private static final Map<Integer, GroupSession> groupSessionMap = new ConcurrentHashMap<>();

    public static void bindSession(Session session, Channel channel) {
        userIdChannelMap.put(session.getUserId(), channel);
//        System.out.println("当前有" + userIdChannelMap.size() + "个用户在线");
        channel.attr(Attributes.SESSION).set(session);
    }

    public static void bindGroupSession(Integer groupId, GroupSession groupSession) {
        groupSessionMap.put(groupSession.getGroupId(), groupSession);
    }

    public static void unBindSession(Channel channel) {
        if (hasLogin(channel)) {
            userIdChannelMap.remove(getSession(channel).getUserId());
            channel.attr(Attributes.SESSION).set(null);
        }
    }

    public static void unBindGroupSession(int groupId) {
        groupSessionMap.remove(groupId);
    }

    public static boolean hasLogin(Channel channel) {
        return channel.hasAttr(Attributes.SESSION) && channel.attr(Attributes.SESSION).get() != null;
    }

    public static boolean hasGroup(int groupId) {
        return groupSessionMap.containsKey(groupId);
    }

    public static Session getSession(Channel channel) {
        return channel.attr(Attributes.SESSION).get();
    }

    public static GroupSession getGroupSession(int groupId) {
        return groupSessionMap.get(groupId);
    }

    public static Channel getChannel(int userId) {
        return userIdChannelMap.get(userId);
    }

    public static ChannelGroup getChannelGroup(int groupId) {
        GroupSession groupSession = groupSessionMap.get(groupId);
        if (groupSession == null) {
            return null;
        }
        return groupSession.getChannelGroup();
    }
}
